package baiqitun.stupro.common.workflow.util;

import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;

/**
 * RepositoryService的封装类
 * @author kedaji
 */
@Service
public class RepositoryUtil {
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 获取最新版本的流程定义
     * @param processDefinitionKey 流程定义KEY（注意流程定义KEY 不等于流程定义Id）
     * @return 流程定义
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public ProcessDefinition getLatestProcessDefinitionByKey(@NotBlank(message = "流程定义key不能为空") String processDefinitionKey){
        return repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey)
                .orderByProcessDefinitionVersion().desc().latestVersion().singleResult();
    }

    /**
     * 获取最新版本的流程定义
     * @param processDefinitionId 流程定义id（注意流程定义KEY 不等于流程定义id）
     * @return 流程定义
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public ProcessDefinition getLatestProcessDefinitionById(@NotBlank(message = "流程定义key不能为空") String processDefinitionId){
        return repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId)
                .orderByProcessDefinitionVersion().desc().latestVersion().singleResult();
    }
}
